#include <iostream>
#include <QFile>
#include "mainwindow.h"
#include "ui_mainwindow.h"

using namespace std;

//ultimatni konstruktor
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{


        ui->setupUi(this); //nastaveni grafiky (musime volat driv nez pouzivame elementy,elementy musi byt nejdriv inicializovane)

        //nulovani casovych displeyu
        ui->currentLcdNumber->display("00:00");
        ui->lengthLcdNumber->display("00:00");

        audioOut = new Phonon::AudioOutput(Phonon::MusicCategory, this); //nastavovani vystupu (zvukovky)
        media = new Phonon::MediaObject(this); //zakladani objektu media slouziciho pro prehravani
        ui->horizontalSlider->setMediaObject(media); //Phonon::seekSlider-posuvnik zobrazujici soucasny stav prehravani, vstupem je nas objekt media
        ui->volumeSlider->setAudioOutput(audioOut); //Phonon::volumeSlider- posuvnik zvuku, zobrazujeme s nim i "MUTE" element. Parametrem je nas hudebni vystup audioOut

        Phonon::createPath(media, audioOut); //propojeni prehravaneho media (objektu) s hudebnim vystupem (zvukovkou)

        connect(media, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(stateChanged(Phonon::State,Phonon::State)));
        connect(media,SIGNAL(totalTimeChanged(qint64)),this,SLOT(setTotal())); //propojeni zajistujici aktualnost zobrazeni lcd displeye s celkovym casem
        media->setTickInterval(500); //nastaveni casoveho intervalu mezi jednotlivymi "tick" signaly media v milisekundach (0,5s)
        connect(media, SIGNAL(tick(qint64)), this, SLOT(tick(qint64))); //propojeni signalu od media o aktualnim casu a jeho zobrazeni na lcd display
        connect(media, SIGNAL(aboutToFinish()), this, SLOT(songFinished())); //propojeni zajistujici obsluhu po dohrani songu


        connect(media, SIGNAL(finished()), this, SLOT(nextSong()));
        initTable();
        playingSong = 0;
    }

//destruktor
MainWindow::~MainWindow()
{
    delete ui;
}

//SLOT obsluhujici nastaveni celkoveho casu songu
void MainWindow::setTotal(){
    QTime displayTime(0, (media->totalTime() / 60000) % 60, (media->totalTime() / 1000) % 60); //prepocet z milisekund na lidsky citelnou formu

    ui->lengthLcdNumber->display(displayTime.toString("mm:ss")); //zobrazime na displey
}

//SLOT obsluhujici time-intervaly (parametr je soucasny time-stav media)
void MainWindow::tick(qint64 time)
{
    QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60); //prepocet z milisekund na lidsky citelnou formu

    ui->currentLcdNumber->display(displayTime.toString("mm:ss")); //zobrazime na displey
}

//SLOT obsluhujici konec pisnicky
void MainWindow::songFinished(){
   ui->currentLcdNumber->display("00:00"); //nulujeme displey
}

//zastaveni prehravani
void MainWindow::on_stopButton_released()
{
    media->stop();
    ui->currentLcdNumber->display("00:00"); //nulujeme current displey
}


//spusteni songu
void MainWindow::on_playButton_released()
{
    if(media->state()==Phonon::StoppedState) //pokud jsme predtim dali "stop",tak se prehraje znovu ten preruseny song
    media->setCurrentSource(source);
    media->play();
}



//pauza prehravani songu
void MainWindow::on_pauseButton_released()
{
    media->pause();
}

//vybirani noveho songu
void MainWindow::on_addButton_released()
{

    //oteviraci dialog, ktery otevre systemove uloziste hudby a vysledek ulozi do kolekce stringu
    QStringList file = QFileDialog::getOpenFileNames(this, tr("Select Music File (*.wav *.mp3)"),
        QDesktopServices::storageLocation(QDesktopServices::MusicLocation));

    //pokud jsme nic nevybrali tak breakujeme
    if (file.isEmpty())
        return;

    //cyklus, kvuli vybrani vice pisnicek zaroven
    for(int i = 0;i < file.size();i++){
        int lastIndex = ui->tableWidget->rowCount();
        //pokud uz nejsou volne radky, jeden pridej
        if(lastIndex == sources.size()){
            ui->tableWidget->insertRow(ui->tableWidget->rowCount());
        }
        QTableWidgetItem * item = new QTableWidgetItem(file.at(i));
        //prida song do kolekce
        sources.append(Phonon::MediaSource(file.at(i)));
        ui->tableWidget->setItem(sources.size() - 1,0, item);
    }



    //jinak nastavujeme vysledek vyberu ve filedialogu jako zdroj hudby a rovnou zacneme prehravat
   source=Phonon::MediaSource (file.at(file.size() - 1));
   media->setCurrentSource(source);
   media->play();
   //jeste aktualizujeme lcd display
   QTime displayTime(0, (media->totalTime() / 60000) % 60, (media->totalTime() / 1000) % 60);
   ui->lengthLcdNumber->display(displayTime.toString("mm:ss"));

}

/**
  inicializace tabulky
  */
void MainWindow::initTable(){
    QStringList name("Playlist");
    ui->tableWidget->setHorizontalHeaderLabels(name);
    connect(ui->tableWidget, SIGNAL(cellClicked(int,int)), this, SLOT(switchSong(int, int)));
}

/**
  zajisti prepnuti pisnicky, po kliku na radek v tabulce
  */
void MainWindow::switchSong(int row, int col){
    cout << "zavolan slot" << endl;
    playingSong = row;
    if(ui->tableWidget->item(row, col)){
        source = Phonon::MediaSource(ui->tableWidget->item(row, col)->text());
        media->setCurrentSource(source);
        media->play();
    }
    cout << media->isSeekable() << " a" << endl;
    cout << media->currentSource().fileName().toStdString() << endl;
}

void MainWindow::nextSong(){
    if(ui->checkBoxRandom->isChecked()){
        playingSong = rand() % sources.size();
    }
    playingSong++;
    if(sources.size() == playingSong){
        playingSong = 0;
    }
    source = Phonon::MediaSource(sources.at(playingSong));
    media->setCurrentSource(source);
    cout << media->state() << endl;
    media->play();
    ui->tableWidget->setCurrentCell(playingSong, 0);
    cout << media->currentSource().fileName().toStdString() << endl;
}

void MainWindow::stateChanged(Phonon::State newState, Phonon::State oldState){
    cout << "zavolan stav" << endl;
    cout << newState << endl;
}

void MainWindow::on_pushButtonload_clicked()
{
    cout << "loading" << endl;
    QString list = QFileDialog::getOpenFileName(this, QString(""), QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
    QFile file(list);
    file.open(QIODevice::ReadOnly);
    QTextStream input(&file);
    while(list != NULL){
        list = input.readLine();
        int lastIndex = ui->tableWidget->rowCount();
        //pokud uz nejsou volne radky, jeden pridej
        if(lastIndex == sources.size()){
            ui->tableWidget->insertRow(ui->tableWidget->rowCount());
        }
        QTableWidgetItem * item = new QTableWidgetItem(list);
        //prida song do kolekce
        sources.append(Phonon::MediaSource(list));
        ui->tableWidget->setItem(sources.size() - 1,0, item);
    }
    sources.removeAt(sources.size() - 1);
    playingSong = 0;
    source = Phonon::MediaSource(sources.at(playingSong));
    media->setCurrentSource(source);
    cout << media->state() << endl;
    media->play();
    ui->tableWidget->setCurrentCell(playingSong, 0);
    file.close();
}

void MainWindow::on_pushButton_2Save_clicked()
{
    cout << "saving" << endl;
    QString list = QFileDialog::getSaveFileName(this, QString("save playlist"), QDesktopServices::storageLocation(QDesktopServices::HomeLocation), QString(""), 0, 0);
    QFile file(list);
    cout << list.toStdString() << endl;
    file.open(QIODevice::WriteOnly);
    QTextStream output(&file);
    for(int i = 0;i < sources.size();i++){
        output << sources.at(i).fileName() << endl;
    }
    file.close();
}
